"use strict";
this.AutoRefresh = function () {};

this.AutoRefresh.prototype = (function () {
    var init, thread, onConfigurationLoaded, areas, initArea, onRedraw;

    init = function () {};

    thread = function (webLayout) {
        var time, i;
        time = (new Date()).getTime();
        for (i = areas.length - 1; i >= 0; i -= 1) {
            if (areas[i].element && !areas[i].paused) {
                if (time - areas[i].last >= areas[i].period) {
                    areas[i].last = time - ((time - areas[i].last) %
                            areas[i].period);
                    webLayout.moduleEvent('contentToBeReplaced',
                            areas[i].element);
                    webLayout.ajaxLib.load(areas[i].url, '', areas[i].element,
                            areas[i].redraw);
                }
            }
        }
    };

    onRedraw = function (webLayout, details) {
        var i;
        if (!(areas instanceof Array)) {
            return;
        }
        for (i = areas.length - 1; i >= 0; i -= 1) {
            if ((areas[i].element === undefined) ||
                    !areas[i].element.parentNode) {
                areas[i].element = webLayout.xPath(areas[i].elementPath)[0];
                initArea(webLayout, areas[i]);
            }
        }
    };

    onConfigurationLoaded = function (webLayout, config) {
        var i;
        if (config[this.NAME] === undefined) {
            return;
        }
        areas = config[this.NAME];
        for (i = areas.length - 1; i >= 0; i -= 1) {
            areas[i].last = (new Date()).getTime();
            areas[i].paused = false;
            areas[i].element = webLayout.xPath(areas[i].elementPath)[0];
            initArea(webLayout, areas[i]);
        }
    };

    initArea = function (webLayout, area) {
        if (!area.element) {
            return;
        }
        webLayout.addEventListener(area.element, 'click', function () {
            area.paused = !area.paused;
        });
        area.redraw = function () {
            webLayout.redraw(area.element);
        };
    };

    return {
        NAME: 'AutoRefresh',
        init: init,
        thread: thread,
        onConfigurationLoaded: onConfigurationLoaded,
        onRedraw: onRedraw
    };
}());